//
//  NSObject+MBGetCurrentController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/4/4.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "NSObject+MBGetCurrentController.h"

@implementation NSObject (MBGetCurrentController)
//-(UIViewController *)getCurrentViewController
//{
//    UIResponder * next = [self nextResponder];
//    do{
//        if ([next isKindOfClass:[UIViewController class]]) {
//            return (UIViewController *)next;
//        }
//        next = [next nextResponder];
//    }while (next !=nil) ;
//    return nil;
//    
//}

/**
 
 当前windows下的控制器
 */
- (UIViewController *)getWindowController
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


/**
 获取当前屏幕上present的控制器
 */
- (UIViewController *)getPresentedViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    
    return topVC;
}
@end
